<template>
  <div class="product-management">
    <!-- 搜索表单 -->
    <a-card>
      <a-form style="width: 100%;" layout="inline" :label-col="{ style: { width: '80px', textAlign: 'left' } }"
        :model="searchForm" @finish="handleSearch">
        <div class="user-form">
          <a-row :gutter="[16, 16]" style="flex: 1;">
            <a-col class="gutter-row" :span="8">
              <a-form-item label="产品名称">
                <a-input v-model:value="searchForm.name" placeholder="请输入产品名称" allowClear />
              </a-form-item>
            </a-col>
            <a-col class="gutter-row" :span="8">
              <a-form-item label="外卖类型">
                <a-select v-model:value="searchForm.type" allowClear>
                  <a-select-option :value="1">主食</a-select-option>
                  <a-select-option :value="2">饮料</a-select-option>
                  <a-select-option :value="3">小吃</a-select-option>
                  <a-select-option :value="4">水果</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col class="gutter-row" :span="8">
              <a-form-item label="是否上架">
                <a-select v-model:value="searchForm.state" allowClear>
                  <a-select-option :value="1">已上架</a-select-option>
                  <a-select-option :value="0">未上架</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col class="gutter-row" :span="8">
              <a-form-item label="营销品类">
                <a-select v-model:value="searchForm.mark" allowClear>
                  <a-select-option :value="1">新品</a-select-option>
                  <a-select-option :value="2">招牌</a-select-option>
                  <a-select-option :value="3">推荐</a-select-option>
                  <a-select-option :value="4">普通</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
          </a-row>
          <div class="form-btn">
            <a-form-item>
              <a-button type="link" @click="resetSearch">重置</a-button>
              <a-button type="primary" html-type="submit">搜索</a-button>
            </a-form-item>
          </div>
        </div>
      </a-form>
    </a-card>

    <!-- 操作按钮 -->
    <a-card style="margin-top: 16px" class="table-body">
      <div class="action-buttons">
        <a-space>
          <a-button type="primary" @click="showAddModal">
            <template #icon><plus-outlined /></template>
            添加外卖
          </a-button>
        </a-space>
      </div>
      <div class="table-contaier" ref="tableContainerRef">
        <a-table :scroll="{ y: tableHeight + 'px' }" :loading="loading" :columns="columns" :data-source="productList"
          :pagination="pagination" :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
          row-key="user_id" @change="handleTableChange">
          <template #bodyCell="{ column, record,index }">
            <template v-if="column.key === 'index'">
              {{index+1}}
            </template>
            <template v-if="column.key === 'image'">
              <a-image :width="40" :src="record.image"
                fallback="" />
            </template>
            <template v-if="column.key === 'type'">
              {{ formatType(record.type) }}
            </template>
            <template v-if="column.key === 'mark'">
              {{ formatMark(record.mark) }}
            </template>
            <template v-if="column.key === 'state'">
              {{ formatState(record.state) }}
            </template>
            <template v-else-if="column.key === 'action'">
              <a-space>
                <a @click="showUpdateModal(record)">修改</a>
                <a-popconfirm title="你确定删除此商品吗?" ok-text="确定" cancel-text="取消" @confirm="confirmDelete(record)">
                  <a>删除</a>
                </a-popconfirm>
              </a-space>
            </template>
          </template>
        </a-table>
      </div>
    </a-card>
    <!-- 添加用户模态框 -->
    <a-modal centered v-model:visible="addModalVisible" :title="addForm.product_id ? '修改外卖信息' : '添加外卖信息'">
      <a-form ref="addFormRef" :labelCol="{ span: 4 }" :model="addForm" :rules="addFormRules">
        <a-form-item label="外卖图片" name="image">
          <upload :url="addForm.image" v-if="addModalVisible" @uploadSuccess="(res) => {
            addForm.image = res.url;
          }" />
        </a-form-item>
        <a-form-item label="外卖名称" name="name">
          <a-input v-model:value="addForm.name" placeholder="请输入外卖名称" />
        </a-form-item>
        <a-form-item label="外卖类型" name="type">
          <a-select v-model:value="addForm.type">
            <a-select-option :value="1">主食</a-select-option>
            <a-select-option :value="2">饮料</a-select-option>
            <a-select-option :value="3">小吃</a-select-option>
            <a-select-option :value="4">水果</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="外卖价格" name="price">
          <a-input v-model:value="addForm.price" placeholder="请输入外卖价格" prefix="￥" suffix="RMB" />
        </a-form-item>
        <a-form-item label="折价格" name="current_price">
          <a-input v-model:value="addForm.current_price" placeholder="请输入折后价" prefix="￥" suffix="RMB" />
        </a-form-item>
        <a-form-item label="是否上架" name="state">
          <a-select v-model:value="addForm.state">
            <a-select-option :value="1">已上架</a-select-option>
            <a-select-option :value="0">未上架</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="外卖特色" name="mark">
          <a-select v-model:value="addForm.mark">
            <a-select-option :value="1">新品</a-select-option>
            <a-select-option :value="2">招牌</a-select-option>
            <a-select-option :value="3">推荐</a-select-option>
            <a-select-option :value="4">普通</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="外卖商家" name="store">
          <a-input v-model:value="addForm.store" placeholder="请输入外卖商家" />
        </a-form-item>
        <a-form-item label="外卖描述" name="desc">
          <a-textarea v-model:value="addForm.desc" showCount :maxlength="100" />
        </a-form-item>
      </a-form>
      <template #footer>
        <a-button key="back" @click="resetAddForm">取 消</a-button>
        <a-button key="submit" type="primary" :loading="addFormLoading" @click="handleAddProduct">确 定</a-button>
      </template>
    </a-modal>
  </div>
</template>

<script>
import { ref, reactive, onMounted, watch } from 'vue'
import {
  message,
  Modal
} from 'ant-design-vue'
import {
  PlusOutlined,
  DownloadOutlined,
  DownOutlined,
  DeleteOutlined,
  UnlockOutlined,
  LockOutlined
} from '@ant-design/icons-vue'
import md5 from 'md5-node'
import { getAllProduct, addProduct, delProduct, updateProduct } from '@/apis/admin/product'
import upload from '../../../components/upload.vue'

export default {
  components: {
    PlusOutlined,
    DownloadOutlined,
    DownOutlined,
    DeleteOutlined,
    UnlockOutlined,
    LockOutlined,
    upload
  },
  setup() {
    // 数据状态
    const productList = ref([])
    const loading = ref(false)
    const selectedRowKeys = ref([])
    const addModalVisible = ref(false)

    const tableContainerRef = ref();
    const tableHeight = ref(600);
    onMounted(() => {
      tableHeight.value = tableContainerRef.value.clientHeight - 88;
    })



    // 分页配置
    const pagination = reactive({
      current: 1,
      pageSize: 8,
      total: 0,
      showSizeChanger: false,
      showTotal: total => `总共 ${total} 条`
    })

    // 搜索表单
    const searchForm = reactive({
      name: '',
      type: '',
      state: '',
      mark: ''
    })


    // 添加用户表单
    const addForm = ref({
      name: '',
      desc: '',
      type: 1,
      price: '',
      current_price: '',
      state: 0,
      store: '',
      mark: 4,
    })
    // 表单验证规则
    const addFormRules = reactive({
      image: [
        { required: true, message: '请选择图片' },
      ],
      name: [
        { required: true, message: '请输入外卖名称' },
      ],
      type: [
        { required: true, message: '请选择外卖类型' },
      ],
      price: [
        { required: true, message: '请输入价格' },
        { pattern: /^\d+(\.\d{1,2})?$/, message: '请输入正确的价格格式（最多两位小数）' },
        {
          validator: (_, value) => {
            if (value < 0) {
              return Promise.reject('价格不能小于0');
            }
            return Promise.resolve();
          }
        }
      ],
      current_price:
        [
          { pattern: /^\d+(\.\d{1,2})?$/, message: '请输入正确的价格格式（最多两位小数）' },
          {
            validator: (_, value) => {
              if (Number(value) >= Number(addForm.value.price)) {
                return Promise.reject('折后价必须小于当前价格');
              }
              return Promise.resolve();
            }
          }
        ],
      state: [
        { required: true, message: '请选择是否上架' },
      ],
      mark: [
        { required: true, message: '请选择外卖特色' },
      ],
    })
    const addFormRef = ref(null);
    const addFormLoading = ref(false);

    const handleAddProduct = () => {
      addFormRef.value.validate().then(async () => {
        addFormLoading.value = true
        try {
          if (!addForm.value.current_price) delete addForm.value.current_price;
          if (addForm.value.product_id) {
            const { product_id, ...params } = addForm.value
            const res = await updateProduct(product_id, params)
            if (res.code === 0) {
              message.success('修改成功')
              addModalVisible.value = false
              resetAddForm()
              fetchProductList()
            } else {
              message.error(res.message)
            }
          } else {
            const res = await addProduct({
              ...addForm.value,
            })

            if (res.code === 0) {
              message.success('添加成功')
              resetAddForm()
              fetchProductList()
            } else {
              message.error(res.message)
            }
          }

        } catch (error) {
          message.error(error.message)
        } finally {

          addFormLoading.value = false
        }

      });
    }
    const resetAddForm = () => {
      addFormRef.value?.resetFields()
      addModalVisible.value = false
      console.log(addModalVisible.value );
      
    }

    const showUpdateModal = (record) => {
      addForm.value = { ...record };
      addModalVisible.value = true;
    }



    // 表格列配置
    const columns = [
      {
        title: '序号',
        dataIndex: 'index',
        key: 'index',
      },
      {
        title: '外卖图片',
        dataIndex: 'image',
        key: 'image'
      },
      {
        title: '外卖名称',
        dataIndex: 'name',
        key: 'name'
      },
      {
        title: '外卖描述',
        dataIndex: 'desc',
        key: 'desc'
      },
      {
        title: '外卖类型',
        dataIndex: 'type',
        key: 'type'
      },
      {
        title: '价格(元)',
        key: 'price',
        dataIndex: 'price'
      },
      {
        title: '折后价(元)',
        key: 'current_price',
        dataIndex: 'current_price'
      },
      {
        title: '是否已上架',
        key: 'state',
        dataIndex: 'state'
      },
      {
        title: '商家',
        key: 'store',
        dataIndex: 'store'
      },
      {
        title: '标记',
        key: 'mark',
        dataIndex: 'mark'
      },
      {
        title: '操作',
        key: 'action'
      }
    ]

    // 生命周期钩子
    onMounted(() => {
      fetchProductList()
    })

    // 方法
    const fetchProductList = async () => {
      try {
        loading.value = true

        const params = {
          page: pagination.current,
          limit: pagination.pageSize,
          ...searchForm,
        }
        for (let keys in params) {
          if (params[keys] === null || params[keys] === undefined || params[keys] === '') delete params[keys]
        }

        const res = await getAllProduct(params)
        if (res.code === 0) {
          productList.value = res.data.list
          pagination.total = res.data.total
        } else {
          message.error(res.message)
        }
      } catch (error) {
        message.error('获取产品列表失败')
      } finally {
        loading.value = false
      }
    }

    const handleSearch = () => {
      pagination.current = 1
      fetchProductList()
    }

    const resetSearch = () => {
      Object.keys(searchForm).forEach(key => {
        if (Array.isArray(searchForm[key])) {
          searchForm[key] = []
        } else {
          searchForm[key] = undefined
        }
      })
      handleSearch()
    }

    const handleTableChange = (pag, filters, sorter) => {
      pagination.current = pag.current
      pagination.pageSize = pag.pageSize
      fetchProductList()
    }

    const onSelectChange = selectedKeys => {
      selectedRowKeys.value = selectedKeys
    }



    const showAddModal = () => {
      addForm.value = {
        name: '',
        desc: '',
        type: 1,
        price: '',
        current_price: '',
        state: 0,
        store: '',
        mark: 4,
      }
      addModalVisible.value = true
    }


    const confirmDelete = async (record) => {
      const res = await delProduct(record.product_id)
      if (res.code === 0) {
        message.success('删除成功')
        fetchProductList()
      } else {
        message.error(res.message)
      }
    }

    function formatType(type) {
      if (type === 1) {
        return '主食'
      } else if (type === 2) {
        return '饮料'
      } else if (type === 3) {
        return '小吃'
      } else if (type === 4) {
        return '水果'
      } else {
        return ''
      }
    }

    function formatState(state) {
      if (state === 1) {
        return '上架'
      } else {
        return '未上架'
      }
    }

    function formatMark(mark) {
      if (mark === 1) {
        return '新品'
      } else if (mark === 2) {
        return '招牌'
      } else if (mark === 3) {
        return '推荐'
      } else {
        return '推荐'
      }
    }

    return {
      formatType,
      formatState,
      formatMark,
      // 状态
      productList,
      loading,
      selectedRowKeys,
      addModalVisible,
      pagination,

      tableContainerRef,
      tableHeight,

      // 表单数据
      searchForm,
      confirmDelete,
      showUpdateModal,


      // 配置
      columns,

      // 方法
      handleSearch,
      resetSearch,
      handleTableChange,
      onSelectChange,
      showAddModal,
      addFormLoading,
      handleAddProduct,
      addFormRules,
      addForm,
      addFormRef,
      resetAddForm
    }
  }
}
</script>

<style lang="less" scoped>
.product-management {
  padding: 20px;
  display: flex;
  flex-direction: column;

  .user-form {
    width: 100%;
    display: flex;
    justify-content: space-between;

    .form-btn {
      min-width: 140px;
    }
  }

  .table-body {
    flex: 1;

    :deep(.ant-card-body) {
      height: 100%;
      display: flex;
      flex-direction: column;

      .table-contaier {
        flex: 1;

        .ant-table {
          height: 100%;
        }
      }

    }
  }
}

.action-buttons {
  display: flex;
  justify-content: space-between;
  margin-bottom: 16px;
}

.ant-card {
  margin-bottom: 16px;
}
</style>